package com.xzsoft.gdwz.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import xz.facade.user.model.Result;

import com.xzsoft.gdwz.jwt.util.JwtHelper;


public class UserInterceptor implements HandlerInterceptor {
	
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}
	
	/**
	 * 校验token信息
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
	    String token = request.getParameter("token");
	    Result result = new Result();
	    //token为空
	    System.out.println("token:"+token);
	    if(token==null || "".equals(token)) {
	    	result.setResult("");
	    	result.setResultCode("C0001");
	    	result.setSuccess(false);
	    	result.setResultMessage("请输入token信息！");
	    	System.out.println("请输入token信息！");
	    	JSONObject jb = JSONObject.fromObject(result);
	    	response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			return false;
	    }
	    
	    //token校验
	    if(JwtHelper.parseJWT(token)==null){
	    	result.setResult("");
	    	result.setResultCode("C0002");
	    	result.setSuccess(false);
	    	result.setResultMessage("token信息无效！");
	    	
	    	System.out.println("token信息无效！");
	    	JSONObject jb = JSONObject.fromObject(result);
	    	response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			return false;
	    }
	    
	    return true;  
	}  


}
